package org.dromara.system.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.dromara.system.domain.AccessToken;
import org.dromara.system.domain.TemplateData;
import org.dromara.system.domain.dto.WxMssDTO;
import org.springframework.boot.system.ApplicationPid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class XcxUtil {

    public final static String APPID = "wxc31ba381c8b3c01f";

    public final static String SECRET= "83a45888e12c06cb64b50c35c2d9e25a";

    public static AccessToken at;

    /**
     * 获取 Access token
     */
    private static void getAccessToken () {
        // 发送请求获取token
        String token = null;
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + APPID + "&secret=" + SECRET;
            token = WXPublicAccountHttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONUtil.parseObj(token);
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        // 创建token对象，并存储
        at = new AccessToken(accessToken, String.valueOf(expiresIn));
        System.out.println(token);
    }

    /**
     * @Description 获取token, 本地缓存有就直接返回，没有就发送请求获取（wx官方api获取token每天有限制，因此需做缓存)
     * @return String
     */
    public static String getToken () {
        if (at == null || at.isExpired()) {
            getAccessToken();
        }
        return at.getAccessToken();
    }

    public static final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

    /**
     * 发送消息
     * @param openid 接送人openid
     * @return
     */
    public String push(String openid) {
        RestTemplate restTemplate = new RestTemplate();
        String url = SEND_INFO_URL + getToken();
        //拼接推送的模板
        WxMssDTO wxMssDTO = new WxMssDTO();
        wxMssDTO.setTouser(openid); //接收人
        wxMssDTO.setTemplate_id("Qfw-8DiDx7DZ4W2uZh-tH-JjzBisG4EyByet0cYTzDU"); //模板
        wxMssDTO.setPage(""); //链接到小程序那个url
        Map<String, TemplateData> map = new HashMap<String, TemplateData>();
        map.put("thing1",new TemplateData("1111"));
        map.put("thing2",new TemplateData("11111"));
        map.put("thing6",new TemplateData("1111"));
        wxMssDTO.setData(map);
        //发送请求
         ResponseEntity<String> responseEntity =
                        restTemplate.postForEntity(url, wxMssDTO, String.class);
        return "";
    }





}
